package com.shinewind.gateway.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
@EnableConfigurationProperties(JwtProperties.class)
public class JwtTemplate {
    @Autowired
    private JwtProperties jwtProperties;
    //解密token
    public Claims parseJwt(String jwt){
        Claims claims;
        try{
            claims = Jwts.parser().setSigningKey(jwtProperties.getSecretKey())
                    .parseClaimsJws(jwt)
                    .getBody();
        }
        catch(ExpiredJwtException e){
            claims = e.getClaims();
        }
        return claims;
    }
    //判断token是否过期
    public Boolean isJwtExpired(String jwt){
        //解密token并获取令牌过期时间
        Claims claims = parseJwt(jwt);
        Date expiration = claims.getExpiration();
        //判断当前日期是否在过期日期之前
        return expiration.before(new Date());
    }
    //验证token
    public Boolean ValidateToken(String jwt){
        return (!isJwtExpired(jwt));
    }
}
